<template>
  <div>
    <van-cell icon="search" v-for="(text, index) in suggestions" :key="index">
      <span
        slot="title"
        v-html="highLight(text)"
        @click="$emit('search', text)"
      ></span>
    </van-cell>
    <!-- <p v-html="str"></p> -->
  </div>
</template>

<script>
import { getSearchList } from '@/api/search'
import { debounce } from 'lodash'
export default {
  name: 'Searchsuggestion',
  components: {},
  props: {
    searchText: {
      type: String,
      required: true,
    },
  },
  data() {
    return {
      suggestions: [],
      // str: '<span style="color: red">World</span>',
    }
  },
  computed: {},
  watch: {
    searchText: {
      handler: debounce(function(val) {
        this.loadSearchSug(val)
      }, 400),
      immediate: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    async loadSearchSug(val) {
      try {
        const { data } = await getSearchList(val)
        console.log(data)
        this.suggestions = data.data.options
      } catch {
        this.$toast('获取数据失败,请稍后再试')
      }
    },
    highLight(text) {
      // return text.replace(/a/gi, `<span style="color:red;">a</span>`)
      const reg = new RegExp(this.searchText, 'gi')
      return text.replace(
        reg,
        `<span style="color:red">${this.searchText}</span>`
      )
    },
  },
}
</script>

<style lang="less" scoped></style>
